<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="canvas-sketchpad1.css">
    <title>Document</title>
</head>

<body>
    <canvas id="canvas"></canvas>
    <script>
        var canvas = document.getElementById('canvas')
        // 注意这里设置宽高的时候没有带 style
        canvas.width = document.documentElement.clientWidth;
        canvas.height = document.documentElement.clientHeight;
        const ctx = canvas.getContext('2d');

        var onoff = false;
        let lastX;
        let lastY;

        var isTouchDevice = ('ontouchstart' in document.documentElement);

        function drawLine(x1, y1, x2, y2) {
            ctx.beginPath();
            ctx.moveTo(x1, y1);
            ctx.lineTo(x2, y2);
            ctx.closePath();
            ctx.lineWidth = 10;
            ctx.lineCap = "round";
            ctx.stroke();

        }


        if (isTouchDevice) {
            canvas.ontouchstart = (e) => {
                lastX = e.touches[0].clientX
                lastY = e.touches[0].clientY
            }

            canvas.ontouchmove = (e) => {
                drawLine(lastX, lastY, e.touches[0].clientX, e.touches[0].clientY)
                lastX = e.touches[0].clientX
                lastY = e.touches[0].clientY
            }
        } else {
            canvas.onmousedown = (e) => {
                onoff = true;
                lastX = e.clientX;
                lastY = e.clientY;
            }
            canvas.onmousemove = (e) => {

                if (onoff) {
                    drawLine(lastX, lastY, e.clientX, e.clientY)
                    lastX = e.clientX
                    lastY = e.clientY
                }
            }
            canvas.onmouseup = () => {
                onoff = false;
            }
        }
    </script>
</body>

</html>